import { login, logout, getInfo } from '@/api/login'
import { register} from "@/api/register";
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from "js-cookie";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    userId: "",
    roles: "",
    shopType: '',
    permissions: [],
    rhUser: {
      nickName: '',
      avatar: ''
    },
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERTYPE: (state, shopType) => {
      state.shopType = shopType
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_RHUSER: (state, user) => {
      state.rhUser = user
    }
  },

  actions: {
    // 登录
    Login({ commit }, params) {
      let {key, userInfo} = params, query = {}, unfamiliarBrowser = '0'
      const username = userInfo.username.trim()
      const identification = process.env['VUE_APP_RULE']
      // let timer = Cookies.get('icarBrowser')
      // if(timer && (timer == username)){
      //   unfamiliarBrowser = '1'
      // }
      unfamiliarBrowser = '1'
      const password = userInfo.password
      const code = userInfo.code.trim() 
      if(key == 'code'){
        unfamiliarBrowser = 1
        query = {
          username, code, identification, unfamiliarBrowser, password: ''
        }
      }else{
        query = {
          username, password, identification, unfamiliarBrowser
        }
      }
      return new Promise((resolve, reject) => {
        login(query).then(res => {
          if(unfamiliarBrowser == '1'){
            setToken(res.token)
            Cookies.set('icarBrowser', username, { expires: 365 })
            commit('SET_TOKEN', res.token)
            resolve({action: 'login'})
          }else{
            resolve({action: 'next', ...res})
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 注册
    appRegister({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        register(userInfo).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          let {permissions, roles, user, shopType} = res
          const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
          // if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
          //   commit('SET_ROLES', process.env['ENV'])
          //   commit('SET_PERMISSIONS', permissions)
          // } else {
          //   commit('SET_ROLES', ['ROLE_DEFAULT'])
          // }
          commit('SET_ROLES', [process.env['VUE_APP_RULE']])
          commit('SET_PERMISSIONS', permissions)
          commit('SET_NAME', user.nickName)
          commit('SET_AVATAR', avatar)
          commit('SET_USERID', user.userId)
          commit('SET_USERTYPE', shopType)
          let rhUser = {
            // deptName: user['dept']['deptName'],
            // deptId: user.deptId,
            nickName: user.nickName,
            avatar: avatar
          }
          commit('SET_RHUSER', rhUser)
          resolve(res)
        })
        // let permissionss = ["*:*:*"]
        // let permissionss = [
        //   "admin:active:list",
        //   "admin:order:list", 
        //   "admin:service:list",
        //   "admin:store:list", 
        //   "admin:user:list", 
        //   "admin:finance:view",
        //   "admin:staff:store",
        //   "admin:setting:list"
        // ]
        // let roles = "admin"
        // let permissionss = [
        //   "store:active:list",
        //   "store:active:action-active",
        //   "store:order:list", 
        //   "store:vip:list", 
        //   "store:finance:view",
        //   "store:finance:action-account",
        //   "store:finance:check-account", 
        //   "store:finance:action-card-person",
        //   "store:finance:action-card-company",
        //   "store:finance:check-company",
        //   "store:staff:store"
        // ]
        // let roles = "store"
        
        
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
